package com.erp.stock.service.impl;

import com.alibaba.fastjson.JSON;
import com.erp.produce.dao.OrderDao;
import com.erp.produce.dto.GoodsInfo;
import com.erp.produce.service.OrderService;
import com.erp.stock.dao.ProcessedProductionStockDao;
import com.erp.stock.entity.ProcessedProductionStock;
import com.erp.stock.service.ProcessedProductionStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ProcessedProductionStockServiceImpl implements ProcessedProductionStockService {
    @Autowired
    ProcessedProductionStockDao dao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    OrderService orderService;

    @Override
    public Boolean insertStocksByOrder(Long orderId) {
        //根据orderID找出对应的产品
        try {
            String goodsInfoStr = orderDao.findById(orderId).get().getGoodInfo();
            List<GoodsInfo> goodsInfos = JSON.parseArray(goodsInfoStr, GoodsInfo.class);
            goodsInfos.forEach((goodsInfo -> {
                ProcessedProductionStock stock = new ProcessedProductionStock();
                stock.setCount(goodsInfo.getGoodsNumber());
                stock.setOrderId(orderId);
                stock.setProcessedGoodsId(goodsInfo.getGoods().getId());
                stock.setProcessedGoodsName(goodsInfo.getGoods().getGoodName());
                stock.setUnit(goodsInfo.getGoodsUnit());
                dao.save(stock);
            }));
            orderService.changeStatus(5,orderId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public List<ProcessedProductionStock> list(Long orderId) {
        return dao.findAllByOrderId(orderId);
    }
}
